package com.tikeyc.mobileplayer.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.tikeyc.mobileplayer.IMusicService;
import com.tikeyc.mobileplayer.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.Event;

import java.io.File;
import java.util.ArrayList;

import domain.Lyric;
import domain.MediaItem;
import service.MusicService;
import utils.LyriUtils;
import utils.TimeUtils;
import view.ShowLyricView;

public class AudioPlayerActivity extends Activity implements View.OnClickListener {

    private static final int PROGRESS = 0;//音频进度
    private static final int Show_Lyric = 1;//歌词

    private ImageView imageViewVoiceAnimation;
    private TextView textViewSinger;
    private TextView textViewSongTitle;
    private TextView textViewSongTime;
    private SeekBar seekBarAudioProgress;
    private Button buttonSwitchPlayType;
    private Button buttonLastAudio;
    private Button buttonStartOrPauseAudio;
    private Button buttonNextAudio;
    private Button buttonShowSongSummary;

    private ShowLyricView center_showLyricView;
    private boolean isExitLyric;//是否存在歌词

    //
    private boolean isNotificationComing;
    private int position;
    private IMusicService iMusicService;
    private ServiceConnection serviceConnection;
    private BroadcastReceiver receiver;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case PROGRESS:{
                    //
                    try {
                        int currentPosition = iMusicService.getCurrentPosition();
                        seekBarAudioProgress.setProgress(currentPosition);

                        int toalDuration = iMusicService.getToalDuration();
                        String current = TimeUtils.getTime(currentPosition,TimeUtils.DATE_FORMAT_HOUR_MINUTE);
                        String toal = TimeUtils.getTime(toalDuration,TimeUtils.DATE_FORMAT_HOUR_MINUTE);
                        textViewSongTime.setText(current.toString() + "/" + toal.toString());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    //
                    handler.removeMessages(PROGRESS);
                    handler.sendEmptyMessageDelayed(PROGRESS,0);
                }
                break;
                case Show_Lyric:{
                    //
                    try {
                        int currentPosition = iMusicService.getCurrentPosition();

                        center_showLyricView.setCurrentPosition(currentPosition);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    //
                    handler.removeMessages(Show_Lyric);
                    handler.sendEmptyMessageDelayed(Show_Lyric,1000);
                }
                break;
                default:
                    break;
            }
        }
    };



    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2017-01-11 12:30:40 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        imageViewVoiceAnimation = (ImageView)findViewById( R.id.imageView_voice_animation );
        textViewSinger = (TextView)findViewById( R.id.textView_singer );
        textViewSongTitle = (TextView)findViewById( R.id.textView_song_title );
        textViewSongTime = (TextView)findViewById( R.id.textView_song_time );
        seekBarAudioProgress = (SeekBar)findViewById( R.id.seekBar_audio_progress );
        buttonSwitchPlayType = (Button)findViewById( R.id.button_switch_play_type );
        buttonLastAudio = (Button)findViewById( R.id.button_last_audio );
        buttonStartOrPauseAudio = (Button)findViewById( R.id.button_start_or_pause_audio );
        buttonNextAudio = (Button)findViewById( R.id.button_next_audio );
        buttonShowSongSummary = (Button)findViewById( R.id.button_show_song_summary );

        center_showLyricView = (ShowLyricView) findViewById(R.id.center_showLyricView);

        buttonSwitchPlayType.setOnClickListener( this );
        buttonLastAudio.setOnClickListener( this );
        buttonStartOrPauseAudio.setOnClickListener( this );
        buttonNextAudio.setOnClickListener( this );
        buttonShowSongSummary.setOnClickListener( this );
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2017-01-11 12:30:40 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == buttonSwitchPlayType ) {
            // Handle clicks for buttonSwitchPlayType
            setMusicPlayerModel();


        } else if ( v == buttonLastAudio ) {
            // Handle clicks for buttonLastAudio
            try {
                iMusicService.palylastMusic();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else if ( v == buttonStartOrPauseAudio ) {
            // Handle clicks for buttonStartOrPauseAudio
            try {
                if (iMusicService != null && iMusicService.isPlayMusic()) {
                    iMusicService.pauseMusic();
                    handler.removeMessages(PROGRESS);
                    handler.removeMessages(Show_Lyric);
                } else {
                    iMusicService.playMusic();
                    handler.sendEmptyMessage(PROGRESS);
                    handler.sendEmptyMessage(Show_Lyric);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else if ( v == buttonNextAudio ) {
            // Handle clicks for buttonNextAudio
            try {
                iMusicService.palyNextMusic();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        } else if ( v == buttonShowSongSummary ) {
            // Handle clicks for buttonShowSongSummary

        }
    }

    private void setMusicPlayerModel() {
        try {
            int music_play_model = iMusicService.getPalyMusicMode();
            String showMessage = null;

            if (music_play_model == MusicService.Music_play_Normal) {
                music_play_model = MusicService.Music_play_Single;
                showMessage = "单曲循环";
            } else if (music_play_model == MusicService.Music_play_Single) {
                music_play_model = MusicService.Music_play_list_cycle;
                showMessage = "列表循环";
            } else if (music_play_model == MusicService.Music_play_list_cycle) {
                music_play_model = MusicService.Music_play_Normal;
                showMessage = "顺序播放";
            }

            iMusicService.setPalyMusicMode(music_play_model);
            Toast.makeText(AudioPlayerActivity.this,showMessage,Toast.LENGTH_SHORT).show();

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {

//        if (iMusicService != null) {
//            try {
//                iMusicService.exitMusic();
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
//        }

        //
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }

        //
        EventBus.getDefault().unregister(this);

        //
        if (serviceConnection != null) {
            unbindService(serviceConnection);
            serviceConnection = null;
//            iMusicService = null;
        }

        //
        handler.removeMessages(PROGRESS);



        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_audio_player);
        //
        initData();
        //
        findViews();
        //
        getData();
        //
        bindAndStartMusicService();
        //
        setListener();

    }



    /**
     * 注册广播 获取音频信息
     */
    private void initData() {


        //1.系统广播注册法
//        receiver = new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                showViewData();
//            }
//        };
//        IntentFilter intentFilter = new IntentFilter(MusicService.MEDIAPLAY_ONPREPARED);
//        registerReceiver(receiver,intentFilter);

        //2.EventBus注册法
        EventBus.getDefault().register(this);
    }

    //需要在EventBus需要在EventBus post消息的自定义回调方法加上@Subscribe(threadMode = ThreadMode.MAIN,sticky = false,priority = 0) 如下：
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = false,priority = 0)
    public void onEventMainThread(MediaItem mediaItem) {

        String msg = "EventBus onEventMainThread收到了消息：" + mediaItem.getName();
        Log.e("TAG",msg);
        showViewData();
    }

    /**
     * 显示音频信息
     */
    private void showViewData() {

        try {
            textViewSinger.setText(iMusicService.getArtist());
            textViewSongTitle.setText(iMusicService.getSongName());

            int toalDuration = iMusicService.getToalDuration();
            seekBarAudioProgress.setMax(toalDuration);
            //定时更新seekBarAudioProgress
            handler.sendEmptyMessage(PROGRESS);

            //定时更新歌词
            LyriUtils lyriUtils = new LyriUtils();
            //传入歌词文件
            String path = iMusicService.getSongPath();
            path = path.substring(0,path.lastIndexOf("."));
            File file = new File(path);
            if (file.exists()){
                file = new File(path + ".txt");
            }
            ArrayList<Lyric> lyrics = lyriUtils.readLyricFile(file);//解析歌词
            center_showLyricView.setLyrics(lyrics);

            if (lyriUtils.isExitLyric()){
                handler.sendEmptyMessage(Show_Lyric);
            }


        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    /**
     * 得到音频索引
     */
    private void getData() {
        //
        isNotificationComing = getIntent().getBooleanExtra(MusicService.Music_Service_Notification,false);
        if (!isNotificationComing) {
            //
            position = getIntent().getIntExtra("position",0);
        }

    }

    /**
     * 绑定MusicService
     */
    private void bindAndStartMusicService() {
        Intent intent = new Intent(this, MusicService.class);
        intent.setAction("com.tikeyc.mobileplayer_musicService_action");
        if (serviceConnection == null) {
            serviceConnection = new ServiceConnection() {
                /**当链接成功回调
                 * @param componentName
                 * @param iBinder
                 */
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    //得到IMusicService
                    iMusicService = IMusicService.Stub.asInterface(iBinder);
                    if (iMusicService != null) {
                        try {
                            if (!isNotificationComing) {
                                iMusicService.openAudio(position);
                            } else {
                                //从状态栏进入
                                showViewData();
                            }

                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }

                }

                /**当断开链接回调
                 * @param componentName
                 */
                @Override
                public void onServiceDisconnected(ComponentName componentName) {
                    if (iMusicService != null) {
                        try {
                            iMusicService.stopMusic();
                            iMusicService = null;
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
        }
        bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
        startService(intent);//这样不至于实例化多个MusicService
    }



    private void setListener() {
        //
        seekBarAudioProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
                    try {
                        iMusicService.seekTo(i);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }
}
